angular.module('App.controllers', ['ngCookies'])

    .controller('HeaderController', ['$scope', '$rootScope','$window','$state',
        function ($scope, $rootScope, $window, $state) {

            var ww = document.body.clientWidth;
            var adjustMenu = function() {
                if (ww < 800) {
                    $(".toggleMenu").css("display", "inline-block");
                    if (!$(".toggleMenu").hasClass("active")) {
                        $(".nav").hide();
                    } else {
                        $(".nav").show();
                    }
                    $(".nav li").unbind('mouseenter mouseleave');
                    $(".nav li a.parent").unbind('click').bind('click', function(e) {
                        // must be attached to anchor element to prevent bubbling
                        e.preventDefault();
                        $(this).parent("li").toggleClass("hover");
                    });
                } else if (ww >= 800) {
                    $(".toggleMenu").css("display", "none");
                    $(".nav").show();
                    $(".nav li").removeClass("hover");
                    $(".nav li a").unbind('click');
                    $(".nav li").unbind('mouseenter mouseleave').bind('mouseenter mouseleave', function() {
                        // must be attached to li so that mouseleave is not triggered when hover over submenu
                        $(this).toggleClass('hover');
                    });
                }
            };

            $scope.$on('$includeContentLoaded', function () {

                $(".nav li a").each(function() {
                    if ($(this).next().length > 0) {
                        $(this).addClass("parent");
                    };
                });

                $(".toggleMenu").click(function(e) {
                    e.preventDefault();
                    $(this).toggleClass("active");
                    $(".nav").toggle();
                });
                adjustMenu();

                $(window).bind('resize orientationchange', function() {
                    ww = document.body.clientWidth;
                    adjustMenu();
                });
                              
            });
            
            $scope.logout = function(){
            	$rootScope.user = null;
                $window.sessionStorage.clear();
                $state.reload();
            };
        }
    ])

    .controller('AppController', ['$scope', '$rootScope', '$state',
        function ($scope, $rootScope, $state) {
            $scope.$on('$viewContentLoaded', function () {
            });

            // 重新登录
            $rootScope.$on('userLoginIntercepted', function (event, data) {
                $state.go('login');
            });

        }
    ])
    //主页
    .controller('homeCtrl', ['$rootScope', '$scope', '$state', '$window', 'Page',
        function ($rootScope, $scope, $state, $window, Page) {
    		//初始化函数
	    	$scope.$on('$viewContentLoaded', function() {
	            $('.popup-with-zoom-anim').magnificPopup({
					type: 'inline',
					fixedContentPos: false,
					fixedBgPos: true,
					overflowY: 'auto',
					closeBtnInside: true,
					preloader: false,
					midClick: true,
					removalDelay: 300,
					mainClass: 'my-mfp-zoom-in'
				});
	            //初始导航
	            $('.flexslider').flexslider({
	      			animation: "slide",
	      			start: function(slider){
	      			  $('body').removeClass('loading');
	      			}
	            });
	        });
	    	
	    	$scope.opened = [];//已开线路
	    	$scope.opened_short = [];//已开线路前十条
	    	$scope.toBeOpen = [];//待开线路
	    	$scope.toBeOpen_short = [];//待开线路前十条
	    	
	    	//初始化线路
	        $scope.init = function () {
	        	//查询已开线路
		        Page.ajaxPost('line/customer/opened.do', {}, function(resp) { 
		            if(resp.resultCode == 1){
		            	$scope.opened = resp.data;
		            	
		            	$(resp.data).each(function(idx, d) {
		            		if(idx < 10){
		            			$scope.opened_short.push(d);
		            		}
		            	});
		            }
		            else{
		            	$scope.opened = [];
		            	$scope.opened_short = [];
		            }
		        });
		        //查询未开线路
		        Page.ajaxPost('line/customer/toBeOpen.do', {}, function(resp) { 
		            if(resp.resultCode == 1){
		            	$scope.toBeOpen = resp.data;
		            	
		            	$(resp.data).each(function(idx, d) {
		            		if(idx < 10){
		            			$scope.toBeOpen_short.push(d);
		            		}
		            	});
		            }
		            else{
		            	$scope.toBeOpen = [];
		            	$scope.toBeOpen_short = [];
		            }
		        });
		        
		        console.log($scope.opened_short);
	        
	        };
	        
	        $scope.init();
	    	
        }
    ])
    //登录
    .controller('loginCtrl', ['$rootScope', '$scope', '$state', '$window', 'Page','$timeout','settings','$http','sessionStore',
        function ($rootScope, $scope, $state, $window, Page, $timeout, settings,$http,sessionStore) {
    		$scope.login = {};
    	
	    	$scope.valdatePhone = function(phone){
				var reg = /^1[3|4|5|7|8]\d{9}$/;
				if(!reg.test(phone)){
					$scope.login.msg = '请输入有效的手机号码';
					return false;
				}
				return true;
			};
			
			$scope.valdatePassword = function(password){
				if(!password || password.length == 0){
					$scope.login.msg = '请填写登陆密码';
					return false;
				}
				return true;
			};

			$scope.submitLogin = function(){
				if($scope.valdatePhone($scope.login.phone) && $scope.valdatePassword($scope.login.password)){
					$("#loginBtn").attr("disabled",true);
	    			$timeout(function(){
	    				$("#loginBtn").attr("disabled",false);
		            },5000);
	    			var param = {
	    					client_id: 'app',
	    					client_secret: 'HvBJ1PkBttbqxeBF46Aa',
	    					grant_type: 'password',
	    					scope: 'read',
	    					username: $scope.login.phone,
	    					password: $.md5($scope.login.password) // md5加密
    				};
	    			$http({
	    				method : 'POST',
	    				url : settings.loginUrl,
	    				data : param,
	    				cache : false
	    			}).success(function(data) {
	    				$rootScope.user = data;
	    				sessionStore.setObject('user', $rootScope.user);
    					Page.notice('登陆成功!');
    					Page.ajaxPostQuiet(settings.userInfoUrl, null, function(resp) {
    						$rootScope.user = angular.extend(resp.data,$rootScope.user);
    						sessionStore.setObject('user', $rootScope.user);
    					},function(resp){});
    					$state.go('home');
	    			}).error(function(response) {
	    				$scope.login.msg = '账号或密码错误';
	    			});
				}
			};
        }
    ])
    //忘记密码
    .controller('forgetPwdCtrl', ['$rootScope', '$scope', '$state', '$window', 'Page','settings',
        function ($rootScope, $scope, $state, $window, Page, settings) {
	    	$scope.forget = {
	    		captchaUrl : settings.imgCaptchaUrl + '?appId=' + settings.appId + '&_d=' + Math.random(),
	    		msg : '',
	    		step : 1,
	    		phone:''
	    	};
	    	
	    	//更新图形验码
			$scope.updateCaptcha = function(){
				$scope.forget.captchaUrl = settings.imgCaptchaUrl + '?appId=' + settings.appId + '&_d=' + Math.random();
			};
			
			$scope.valdateImageCaptcha = function(captcha){
				var reg = /^[A-Za-z0-9]{4}$/;
				if(reg.test(captcha)){
					return true;
				}else{
					$scope.forget.msg = "请输入有效图形验证码！";
					return false;
				}
			};
			
			$scope.valdatePhone = function(phone){
				var reg = /^1[3|4|5|7|8]\d{9}$/;
				if(!reg.test(phone)){
					$scope.forget.msg = '请输入有效的手机号码';
					return false;
				}
				return true;
			};
			
			//验证短信验证码
			$scope.valdateSmsCaptcha = function(captcha){
				var reg = /^[A-Za-z0-9]{6}$/;
				if(reg.test(captcha)){
					return true;
				}else{
					$scope.forget.msg = "请输入正确的短信验证码！";
					return false;
				}
			};
			
			$scope.valdatePassword = function(password,repassword){
				if(!password || password.length < 6){
					$scope.forget.msg = '密码长度不小于6位';
					return false;
				}
				if(!repassword || repassword.length < 6){
					$scope.forget.msg = '密码长度不小于6位';
					return false;
				}
				if(password != repassword){
					$scope.forget.msg = '重复密码不正确';
					return false;
				}
				return true;
			};
			
			$scope.to1Step = function() {
				$scope.updateCaptcha();
				$scope.forget.step = 1;
				$scope.forget.msg = '';
				$scope.forget.password = '';
				$scope.forget.repassword = '';
				$scope.forget.smsCaptcha = '';
			};
    	
			$scope.to2Step = function() {
				if($scope.valdateImageCaptcha($scope.forget.imgCaptcha) && $scope.valdatePhone($scope.forget.phone)){
					var param = {
						appId: settings.appId,
						phone: $scope.forget.phone,
						captcha : $scope.forget.imgCaptcha
					};
					Page.ajaxPostQuiet(settings.smsCaptchaUrl, param, function(resp) {
						$scope.forget.msg = '短信验证码已发送';
						$scope.forget.step = 2;
		        	},function(resp){
		        		$scope.updateCaptcha();
		        	});
				}else{
					$scope.updateCaptcha();
				}
				
			};
			
			$scope.submitRePassword = function() {
				if($scope.valdateSmsCaptcha($scope.forget.smsCaptcha) && $scope.valdatePassword($scope.forget.password, $scope.forget.repassword)){
					var param = {
						phone: $scope.forget.phone,
						captcha: $scope.forget.smsCaptcha,
						password : $.md5($scope.forget.password)
					};
					Page.ajaxPostQuiet(settings.forgetPasswordUrl, param, function(resp) {
						Page.notice('重置密码成功!');
						$state.go('login');
		        	},function(resp){
		        		$scope.forget.msg = resp.resultDes;
		        	});
				}
				
			};
    	
        }
    ])
    //服务公告
    .controller('serviceCtrl', ['$rootScope', '$scope', '$state', '$window', 'Page',
        function ($rootScope, $scope, $state, $window, Page) {
	    	
    	
    	
        }
    ])
    //乘客须知
    .controller('noticeCtrl', ['$rootScope', '$scope', '$state', '$window', 'Page',
        function ($rootScope, $scope, $state, $window, Page) {
	    	
    	
    	
        }
    ])
    //需求调查
    .controller('researchCtrl', ['$rootScope', '$scope', '$state', '$window', 'Page', '$compile',
        function ($rootScope, $scope, $state, $window, Page, $compile) {
	    	//初始化函数
    		/*
	    	$scope.$on('$viewContentLoaded', function() {
		    	var map = new AMap.Map('map', {
		            resizeEnable : true,
		            zoom : 12,
		            zooms : [4, 18]
		        });
	    	});
	    	*/
    	
	    	$scope.routeStat = {};
	        // $scope.routeStat.startStopName = '11111';
	        // $scope.routeStat.endStopName = '2222222';
	        $scope.busStops = [];  //数据源取出的站点信息
	        $scope.center = {};    //当前中心
	        $scope.nearByNum = 20; //显示附件站点数
	        $scope.displayedMarkers = [];  //已经显示的marker
	        $scope.selectedMarker = {}; //当前选中的marker
	        // $scope.startMarker = {};
	        // $scope.endMarker = {};
	        $scope.selectedPolyline = {};
	        $scope.searchFlag = false;  //只有通过搜索框的定位，才触发moveend事件
	
	        //地图初始化
	        $scope.init = function (id) {
	
	            var map = new AMap.Map(id, {
	                resizeEnable : true,
	                zoom : 12,
	                zooms : [4, 18]
	            });
	
	            //map.setMap.setMapStyle('amap://styles/light');
	
	            //加载工具条
	            map.plugin(['AMap.ToolBar'], function() {
	                var toolBar = new AMap.ToolBar();
	                map.addControl(toolBar);
	            });
	
	            //加载鹰眼
	            /*map.plugin(["AMap.OverView"], function() {
	                var view = new AMap.OverView();
	                map.openOverView = function() {
	                    view.open();
	                }
	                map.addControl(view);
	            });*/
	
	            /*map.plugin(["AMap.Geocoder"], function() {
	                var geocoder = new AMap.Geocoder({
	                    radius : 1000,
	                    extensions : "all"
	                });
	                map.geoQuery = function(points, callback, errorback, parms) {
	                    geocoder.getAddress(points, function(status, geoResult) {
	                        if (status == 'complete' && geoResult.info === 'OK') {
	                            if (callback) {
	                                callback(status, geoResult, parms);
	                            }
	                        } else {
	                            if (errorback) {
	                                errorback(parms);
	                            }
	                        }
	                    });
	                }
	            });*/
	
	            //加载定位插件
	            map.plugin('AMap.Geolocation', function () {
	                geolocation = new AMap.Geolocation({
	                    enableHighAccuracy: true, //是否使用高精度定位，默认:true
	                    timeout: 10000,           //超过10秒后停止定位，默认：无穷大
	                    maximumAge: 0,            //定位结果缓存0毫秒，默认：0
	                    convert: true,            //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
	                    showButton: false,        //显示定位按钮，默认：true
	                    showMarker: false,        //定位成功后在定位到的位置显示点标记，默认：true
	                    showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
	                    zoomToAccuracy:false      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
	                });
	
	                map.addControl(geolocation);
	
	                //geolocation.getCurrentPosition(); //精准定位
	                //geolocation.getCityInfo();        //定位到城市
	
	                AMap.event.addListener(geolocation, 'complete', function (_point) {
	                    Page.notice('定位成功：经度' + _point.position.getLng() + '; 维度：' + _point.position.getLat());
	                });
	                AMap.event.addListener(geolocation, 'error', function (_point) {
	                    Page.notice('定位失败');
	                });      
	            });
	
	            //初始中心点
	            $scope.center = map.getCenter();
	
	            //加载搜索插件
	            AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'],function(){
	                var autoOptions = {
	                    city: "武汉",
	                    input: "keyword"//使用联想输入的input的id
	                };
	                autocomplete= new AMap.Autocomplete(autoOptions);
	                var placeSearch = new AMap.PlaceSearch({
	                    city:'武汉',
	                    map:map
	                });
	                AMap.event.addListener(autocomplete, "select", function(e){
	                    $scope.searchFlag = true;
	                    placeSearch.search(e.poi.name);
	                });
	            });
	
	            return map;
	
	        };
	
	        $scope.map = $scope.init('map');
	
	        //显示站点
	        Page.ajaxPost('../routeStat/stops.do', {}, function(resp) {
	            //摘录所有站点信息
	            $(resp.data.rows).each(function(i, _busStop) {
	                var busStop = {'stopId':_busStop.stopId, 'stopName': _busStop.stopName, 'lng': _busStop.lng, 'lat': _busStop.lat};
	                $scope.busStops.push(busStop);
	            });
	            
	            //计算所有站点与当前中心点的距离
	            $scope.calcDistance();
	
	            //显示距离最近的站点
	            $scope.showStops($scope.nearByNum);
	        });
	
	        $scope.calcDistance = function () {
	            //Page.notice($scope.center.getLng());
	
	            $($scope.busStops).each(function (i, _busStop) {
	                $scope.busStops[i].distance = $scope.center.distance([_busStop.lng, _busStop.lat]);
	            });
	
	            //排序
	            $scope.busStops.sort(function (a, b) {
	                return (a.distance < b.distance) ? -1 : 1;
	            });
	
	        };
	
	        $scope.showStops = function (nearByNum) {
	
	            // 删除历史marker和infoWindow
	            $($scope.map.getAllOverlays('marker')).each(function (i , _marker) {
	                if( _marker != $scope.startMarker && _marker != $scope.endMarker){
	                    $scope.map.remove(_marker);
	                }
	            });
	            // $scope.map.remove($scope.displayedMarkers);
	            $scope.map.clearInfoWindow();
	            $scope.displayedMarkers = [];
	            //
	
	            //显示marker
	            for(var i = 0 ; i < nearByNum ; i++){
	                var marker = new AMap.Marker({
	                    icon: '../assets/admin/img/mark_default.png',
	                    // content: '<div>1111</div>',
	                    position: [$scope.busStops[i].lng, $scope.busStops[i].lat],
	                    extData: {'stopId':$scope.busStops[i].stopId, 'stopName':$scope.busStops[i].stopName, 'stopLng':$scope.busStops[i].lng, 'stopLat':$scope.busStops[i].lat}
	                });
	                // marker.setAnimation('AMAP_ANIMATION_DROP');
	                marker.setMap($scope.map);
	
	                //设置标签
	                marker.setLabel({
	                    offset: new AMap.Pixel(8, 30),
	                    content: $scope.busStops[i].stopName
	                });
	
	                $scope.displayedMarkers.push(marker);
	            }
	
	
	            // 信息弹框
	            $($scope.displayedMarkers).each(function (i, _marker) {
	
	                _marker.on('click', function (e) {
	
	                    var html = '<div>' +
	                        '<div>'+
	                        '<div class="info" style="border: solid 1px silver;">'+
	                        '   <div class="info-top" style="position: relative;background: none repeat scroll 0 0 #F9F9F9;border-bottom: 1px solid #CCC;border-radius: 5px 5px 0 0;">' +
	                        '       <div style="display: inline-block; color: #333333;font-size: 14px; font-weight: bold;line-height: 31px;padding: 0 10px;">' +  _marker.getExtData().stopName + '</div>' +
	                        '       <img style="position: absolute;top: 10px;right: 10px;transition-duration: 0.25s;" src="http://webapi.amap.com/images/close2.gif" ng-click="map.clearInfoWindow()">' +
	                        '   </div>' +
	                        '   <div class="info-middle" style="background-color: white; font-size: 12px;padding: 6px;line-height: 20px;">' +
	                        '       <button type="button" class="btn-defaul" ng-click="setStart()"><i class="fa fa-bus"> 设为起点</i></button>' +
	                        '       <button type="button" class="btn-defaul" ng-click="setEnd()"><i class="fa fa-bus"> 设为终点</i></button>' +
	                        '   </div>' +
	                        '   <div class="info-bottom" style="height: 0px;width: 100%;clear: both;text-align: center;">' +
	                        '       <img style="position: relative; z-index: 104;" src="http://webapi.amap.com/images/sharp.png">' +
	                        '   </div>'+
	                        '</div>' +
	                        '</div>' +
	                        '</div>';
	
	
	                    var template = angular.element(html);
	
	                    //编译模板
	                    var Element = $compile(template)($scope);
	
	                    infoWindow = new AMap.InfoWindow({
	                        isCustom: true,
	                        offset: new AMap.Pixel(15, -50),
	                        content: Element[0]
	                    });
	
	                    infoWindow.open($scope.map, e.target.getPosition());
	                    $scope.selectedMarker = _marker;
	                });
	            });
	        };
	
	        //注册地图拖动事件
	        var clickEventListener = $scope.map.on('dragend', function(e) {
	            $scope.center = $scope.map.getCenter();
	            $scope.calcDistance($scope.center);
	            $scope.showStops($scope.nearByNum);
	        });
	
	        //注册地图缩放事件
	        var clickEventListener = $scope.map.on('zoomend', function(e) {
	            $scope.center = $scope.map.getCenter();
	            $scope.calcDistance($scope.center);
	            $scope.showStops($scope.nearByNum);
	        });
	
	        //注册地图缩放事件
	        var clickEventListener = $scope.map.on('moveend', function(e) {
	            if( $scope.searchFlag == true){
	                $scope.center = $scope.map.getCenter();
	                $scope.calcDistance($scope.center);
	                $scope.showStops($scope.nearByNum);
	                $scope.searchFlag = false;
	            }
	        });
	
	        //设为起点
	        $scope.setStart = function() {
	            //上次的marker恢复默认样式
	            if( typeof $scope.startMarker == 'object') {
	                $scope.startMarker.setIcon('../assets/admin/img/mark_default.png');
	            }
	
	            $scope.startMarker = $scope.selectedMarker;
	            $scope.startMarker.setIcon('../assets/admin/img/mark_start.png');
	            $scope.startMarker.hide();
	            $scope.startMarker.setAnimation('AMAP_ANIMATION_DROP');
	            $scope.startMarker.setzIndex(200);
	            $scope.startMarker.show();
	
	            $($scope.displayedMarkers).each(function (i, _marker) {
	                if( _marker != $scope.startMarker && _marker != $scope.endMarker){
	                    _marker.setIcon('../assets/admin/img/mark_default.png');
	                }
	            });
	
	            //起点-终点连接线
	            if( typeof $scope.startMarker == 'object' && typeof $scope.endMarker == 'object') {
	                $scope.map.remove($scope.selectedPolyline);
	                var lineArr = [
	                    [$scope.startMarker.getPosition().lng, $scope.startMarker.getPosition().lat],
	                    [$scope.endMarker.getPosition().lng, $scope.endMarker.getPosition().lat]
	                ];
	                $scope.selectedPolyline = new AMap.Polyline({
	                    path: lineArr,          //设置线覆盖物路径
	                    strokeColor: "#B4EEB4", //线颜色
	                    strokeOpacity: 0.9,       //线透明度
	                    strokeWeight: 6,        //线宽
	                    strokeStyle: "solid",   //线样式
	                    showDir: true,
	                    strokeDasharray: [10, 5] //补充线样式
	                });
	                $scope.selectedPolyline.setMap($scope.map);
	            }
	
	            $scope.map.clearInfoWindow();
	
	            $scope.routeStat.startStopId = $scope.startMarker.getExtData().stopId ;
	            $scope.routeStat.startStopName = $scope.startMarker.getExtData().stopName ;
	            $scope.routeStat.startStopLng = $scope.startMarker.getExtData().stopLng ;
	            $scope.routeStat.startStopLat = $scope.startMarker.getExtData().stopLat ;
	
	        };
	
	        //设为终点
	        $scope.setEnd = function() {
	            //上次的marker恢复默认样式
	            if( typeof $scope.endMarker == 'object') {
	                $scope.endMarker.setIcon('../assets/admin/img/mark_default.png');
	            }
	
	            $scope.endMarker = $scope.selectedMarker;
	            $scope.endMarker.setIcon('../assets/admin/img/mark_end.png');
	            $scope.endMarker.hide();
	            $scope.endMarker.setAnimation('AMAP_ANIMATION_DROP');
	            $scope.endMarker.setzIndex(200);
	            $scope.endMarker.show();
	
	            $($scope.displayedMarkers).each(function (i, _marker) {
	                if( _marker != $scope.startMarker && _marker != $scope.endMarker){
	                    _marker.setIcon('../assets/admin/img/mark_default.png');
	                }
	            });
	
	            //起点-终点连接线
	            if( typeof $scope.startMarker == 'object' && typeof $scope.endMarker == 'object') {
	                $scope.map.remove($scope.selectedPolyline);
	                var lineArr = [
	                    [$scope.startMarker.getPosition().lng, $scope.startMarker.getPosition().lat],
	                    [$scope.endMarker.getPosition().lng, $scope.endMarker.getPosition().lat]
	                ];
	                $scope.selectedPolyline = new AMap.Polyline({
	                    path: lineArr,          //设置线覆盖物路径
	                    strokeColor: "#B4EEB4", //线颜色
	                    strokeOpacity: 0.9,       //线透明度
	                    strokeWeight: 6,        //线宽
	                    strokeStyle: "solid",   //线样式
	                    showDir: true,
	                    strokeDasharray: [10, 5] //补充线样式
	                });
	                $scope.selectedPolyline.setMap($scope.map);
	            }
	            $scope.map.clearInfoWindow();
	
	            $scope.routeStat.endStopId = $scope.endMarker.getExtData().stopId ;
	            $scope.routeStat.endStopName = $scope.endMarker.getExtData().stopName ;
	            $scope.routeStat.endStopLng = $scope.endMarker.getExtData().stopLng ;
	            $scope.routeStat.endStopLat = $scope.endMarker.getExtData().stopLat ;
	
	        };
	
	        $scope.save = function () {
	
	            Page.ajaxPost('../routeStat/add.do', $scope.routeStat, function() {
	                Page.notice('登记成功！');
	            });
	        };
        }
    ])
;
